package com.bawei.module_shop;

import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
//import com.alipay.sdk.app.EnvUtils;
//import com.alipay.sdk.app.PayTask;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bawei.library_base.RouterPath;
import com.bawei.library_base.mvp.v.BaseFragment;
import com.bawei.library_base.room.good.Good;
import com.bawei.library_base.room.good.GoodDatabase;
//import com.bawei.module_shop.zfb.PayResult;
//import com.bawei.module_shop.zfb.util.OrderInfoUtil2_0;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;

import org.jetbrains.annotations.NotNull;

import java.util.Collections;
import java.util.List;

@Route(path = RouterPath.Shop.PAGER_SHOP)
public class ShopFragment extends BaseFragment  {


    private CheckBox qx;
    private TextView zongjia;
    private TextView jiesuan;
    private SwipeRecyclerView rec;
    private List<Good> allGood;
    private ShopAdapter shopAdapter;

    private float isZoo;

    @Override
    public int beanLayout() {
        return R.layout.fragment_shop;
    }

    @Override
    public void initView() {


        rec = (SwipeRecyclerView) findViewById(R.id.rec);
        rec.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        qx = (CheckBox) findViewById(R.id.qx);
        zongjia = (TextView) findViewById(R.id.zongjia);
        jiesuan = (TextView) findViewById(R.id.jiesuan);

    }

    @Override
    public void initData() {




        //取出数据库数据
        getadapter();

        //拖拽
        Sideslip();

        //购物车的点击事件

        //购买,结算
        BuyShop();


    }

    private void BuyShop() {
        jiesuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isZoo==0){
                    ToastUtils.showShort("买不上");
                }else {
//                    EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
//                    payV2();
                    ARouter.getInstance().build(RouterPath.OrderGoods.ORDER_GOODS)
                            .navigation();


                }
            }
        });
    }


    private void getadapter() {
        allGood = GoodDatabase.getInstance(getContext()).getGoodDao().getAllGood();

        shopAdapter = new ShopAdapter(allGood);
        //侧滑删除
        SideslipDelete();

        //购物车逻辑
        goShop();

        rec.setAdapter(shopAdapter);


        //点击事件，，++   --
        shopAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {
                List<Good> data = shopAdapter.getData();
                Good good = data.get(position);

                //判断子item的点击事件
                //++
                if (view.getId()==R.id.jia){
                    good.setCount(good.getCount()+1);
                    TextView num = (TextView) adapter.getViewByPosition(position, R.id.shuliang);

                    num.setText(""+good.getCount());
                    GoodDatabase.getInstance(getContext()).getGoodDao().update(good);
                    money(data);
                }

                //--
                if (view.getId()==R.id.jian){
                    good.setCount(good.getCount()-1);
                    TextView num = (TextView) adapter.getViewByPosition(position, R.id.shuliang);
                    num.setText(""+good.getCount());

                    if (good.getCount()<=0){
                        num.setText("0");
                        good.setCount(0);
                        GoodDatabase.getInstance(getContext()).getGoodDao().update(good);
                       ToastUtils.showShort("数量只能为0");
                    }
                    money(data);
                }

                //是否选中
                if (view.getId()==R.id.check){
                    CheckBox checkBox = (CheckBox) adapter.getViewByPosition(position, R.id.check);
                    good.setCheck(checkBox.isChecked());
                    GoodDatabase.getInstance(getContext()).getGoodDao().update(good);

                    int item_isCheck=0;

                    for (Good datum : shopAdapter.getData()) {
                        if (datum.isCheck()){
                            item_isCheck++;
                        }
                    }

                    if (item_isCheck==shopAdapter.getData().size()){
                        qx.setChecked(true);
                    }else {
                        qx.setChecked(false);
                    }

                    money(data);
                }

            }
        });


        //全选
        qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                for (Good datum : shopAdapter.getData()) {
                    datum.setCheck(qx.isChecked());

                    GoodDatabase.getInstance(getContext()).getGoodDao().update(datum);
                }

                money(shopAdapter.getData());
                shopAdapter.notifyDataSetChanged();

            }
        });

    }

    private void goShop() {
        float all_money=0;
        int item_isCheck=0;
        for (Good good : allGood) {
            if (good.isCheck()){
                all_money= all_money+ good.getCount()*+Float.parseFloat(good.getPrice());
                item_isCheck++;
            }
        }
        //判断是否上面的item全部选中
        if (item_isCheck==allGood.size()){
            qx.setChecked(true);
        }else {
            qx.setChecked(false);
        }
        //算总价
        money(allGood);
    }

    private void money(List<Good> allGood) {
        float all_money=0;
        for (Good good : allGood) {
            if (good.isCheck()){
                all_money=all_money+good.getCount()*Float.parseFloat(good.getPrice());
            }
        }
        isZoo=all_money;
        zongjia.setText(""+all_money);
    }


    //侧滑删除或者顶置
    private void SideslipDelete() {
        rec.setSwipeMenuCreator(new SwipeMenuCreator( ) {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {
                SwipeMenuItem swipeMenuItem=new SwipeMenuItem(getActivity())
                        .setText("删除")
                        .setBackgroundColor(Color.RED)
                        .setWidth(200)//菜单宽度
                        .setHeight(RecyclerView.LayoutParams.MATCH_PARENT);//菜单高度

                SwipeMenuItem swipeMenuItem1=new SwipeMenuItem(getActivity())
                        .setText("置顶")
                        .setBackgroundColor(Color.BLUE)
                        .setWidth(200)//菜单宽度
                        .setHeight(RecyclerView.LayoutParams.MATCH_PARENT);//菜单高度

                rightMenu.addMenuItem(swipeMenuItem);
                rightMenu.addMenuItem(swipeMenuItem1);
            }
        });

        //删除的点击事件
        rec.setOnItemMenuClickListener((menuBridge, adapterPosition) -> {
            //进行菜单操作，必须关闭菜单
            menuBridge.closeMenu();
            //获取当前要操作的菜单
            int direction = menuBridge.getDirection();
            //菜单里item的下标
            int position = menuBridge.getPosition();
            Log.i("4444444TAG", "onItemClick: "+adapterPosition);
            if (position==0){
                allGood.remove(adapterPosition);
                GoodDatabase.getInstance(getContext()).getGoodDao().delete(allGood.get(adapterPosition));
                shopAdapter.notifyItemRemoved(adapterPosition);
            }
        });
    }

    //拖拽
    private void Sideslip() {

        rec.setLayoutManager(new LinearLayoutManager(getContext()));
        rec.setLongPressDragEnabled(true); // 拖拽排序，默认关闭。
        rec.setItemViewSwipeEnabled(false); // 侧滑删除，默认关闭。
        rec.setOnItemMoveListener(new OnItemMoveListener( ) {
            @Override
            public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
                // 此方法在Item拖拽交换位置时被调用。
                // 第一个参数是要交换为之的Item，第二个是目标位置的Item。
                // 交换数据，并更新adapter。
                int fromPosition = srcHolder.getAdapterPosition();
                int toPosition = targetHolder.getAdapterPosition();
                Collections.swap(allGood, fromPosition, toPosition);
                shopAdapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }
            @Override
            public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {
                // 此方法在Item在侧滑删除时被调用。
                // 从数据源移除该Item对应的数据，并刷新Adapter。
                int position = srcHolder.getAdapterPosition();
                allGood.remove(position);
                shopAdapter.notifyItemRemoved(position);
            }
        });


    }












//    /**
//     * 用于支付宝支付业务的入参 app_id。
//     */
//    public static final String APPID = "2021000117671224";
//
//    /**
//     * 用于支付宝账户登录授权业务的入参 pid。
//     */
//    public static final String PID = "";
//
//    /**
//     * 用于支付宝账户登录授权业务的入参 target_id。
//     */
//    public static final String TARGET_ID = "";
//
//    /**
//     *  pkcs8 格式的商户私钥。
//     *
//     * 	如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
//     * 	使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
//     * 	RSA2_PRIVATE。
//     *
//     * 	建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
//     * 	工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
//     */
//    public static final String RSA2_PRIVATE = "MIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQCFU1L5Jdh2YZa9CuhY92lXRhCTVQiLoacN2H1XybIOA7pVstWGpn5tXUxyHBSUfMHbHmmG6i4WMm1511+qsSAdATa5dZL8nGQzJ7AwjXN6Iq0bbPBsrB8WrAY2ORnWWF5NTO5weLFtx6WZ2vLm37/DJKdUEVt6EiFOiEu1VvkfPUCffK3wyL591jnv+JKtNuIBOAk6XQCchcjj48zvQcX5ufppchbwd6nPhEsR6vOFbTjmt9TNV78U0Sw6nvGx9nm99Zlt/+aMArAhnnpaSUV+L9mwIhWTqTFplZ6jDq5tRYpkEw72WiijwqA52EUf1/EHQ3zfWPPj94GAcroAb80DAgMBAAECggEAVcEPaFNQVGxWkUc3xSl1pv3Y4XrbITybf4tUq6d+kAcTzdVWA+KJBPzyk56+GffYlICOLYnolLxgr/K4hMiiuCU0trsKDNLmnASWDdSdhtxQ7Yf3aF6ZLHL/F9dIaBa0qRGnd84ZiVvVhw1OGPOnmvOzcJ4tcWnB5IpD7+J+H/nKOMFWoIbo8EPxQWRz1+FR+flFv2xGhmM7LGQN9ofrjsNNRkzReFh46Wv1i03y1D7KBRO/V2pRuIy1B7fUtRWGmm2hg7HwIwW8rqhY+TTjGNhQHbhOyS9Xdm+N/A9RxCSOWxjWeH8bpTKxNSGtFLZcCMocb6ykYWsz2vTd53TLuQKBgQDioOsjjtROonqYPKnhmEgOLY8VgwFH4xmzAjFuq/6yX6CdPBf6s575TV5kew9+UbnQQ3AXH1lX4yuw5nds/swi1gya+IC3RWEdBJD6YhyeRJQRWJh8q0fNBX7SEfXUtcAx/vjerC0552nTKOpOd7Ry/f6P26Tfcu5+mhB85gf3FwKBgQCWmsvF+Qz4MO9Wuc0jfC5Snpdx5jGqY0Iik6TJXVjE6h6JvO6X4RUAAZASNftlQLY080ny8iqh/RGg1W1ym8tstvi3thZ0b9BPH2DpB+xAh8E/dChSNrRiJr6SiNFMTsOGXtoVXZgE2JjSRAqlQaiB2WZq7f3X8/Szf8MOn6bM9QJ/MnWh5Ujn/JowsbTQHmrJoF6EfUWuA1ONZU4Xs4yYKR8ho+C9dhSIUPnpCnZb/MQ1myloy70vJ2JtV/X4oUwaJ6eBJwAtqKDJ/qwFm7o8pQCf9zzCtv9r/To8Aon9Ml9Fa9xZjTrI1xuvdFSn1tDQXMow49cD3ry4XXfwM98D5wKBgD22ir/CET12l+ya0GO1FCpI0Fgc8scWS1ht1b2p4aE3KnJYmBBmbDuHaGj989kGzmMeOnQyJaQhVmLociPfkVkoFPz6wXLPCrYRbp2u4HGE73w39fnSbtI1fCwBono5YEekgIr2wj9iHiUzOoWDRTCITD6O7VDbp68SMHTCmRAtAoGBAN71/mXkmubvG5hjd74SSa3n0tzFJvWwCq0X8lkLnDqL+c5BW87q2dCJcXuSk5OJwTOE6n0KILbq/vHtaKfkV4QBdOzS8AQCDIY26zxauR4+fAhtMeBXjc4bjoHv6/6WRuCUZysBxYbOe7LEkEr1jmsN6SrYAGBRZlyPcAd31ccf";
//    public static final String RSA_PRIVATE = "";
//
//    private static final int SDK_PAY_FLAG = 1;
//    private static final int SDK_AUTH_FLAG = 2;
//
//    @SuppressLint("HandlerLeak")
//    private Handler mHandler = new Handler() {
//        @SuppressWarnings("unused")
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case SDK_PAY_FLAG: {
//                    @SuppressWarnings("unchecked")
//                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
//                    /**
//                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
//                     */
//                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
//                    String resultStatus = payResult.getResultStatus();
//                    // 判断resultStatus 为9000则代表支付成功
//                    if (TextUtils.equals(resultStatus, "9000")) {
//                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                      ToastUtils.showShort("支付成功");
//                    } else {
//                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付失败");
//                    }
//                    break;
//                }
//
//            }
//        };
//    };
//
//
//    /**
//     * 支付宝支付业务示例
//     */
//    public void payV2() {
//        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
//
//            return;
//        }
//
//        /*
//         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
//         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
//         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
//         *
//         * orderInfo 的获取必须来自服务端；
//         */
//        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
//        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
//        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
//
//        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
//        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
//        final String orderInfo = orderParam + "&" + sign;
//
//        final Runnable payRunnable = new Runnable() {
//
//            @Override
//            public void run() {
//                PayTask alipay = new PayTask(getActivity());
//                Map<String, String> result = alipay.payV2(orderInfo, true);
//                Log.i("msp", result.toString());
//
//                Message msg = new Message();
//                msg.what = SDK_PAY_FLAG;
//                msg.obj = result;
//                mHandler.sendMessage(msg);
//            }
//        };
//
//        // 必须异步调用
//        Thread payThread = new Thread(payRunnable);
//        payThread.start();
//    }


}